package com.jcli.novel_t.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * 可用，加载文件内容，更改文件内容，替换文件内容，保存文件内容。
 */


public class TextFileProcessorUI03 extends JFrame {
    private JTextArea textArea; // 文本输入区域
    private JButton saveButton; // 保存按钮
    private JButton convertButton; // 开始转换按钮
    private JTextArea resultTextArea; // 结果文本区域
    private Properties properties; // 属性配置
    private JScrollPane sharedScrollPane; // 共享的滚动窗格

    public TextFileProcessorUI03(Properties properties) {
        this.properties = properties;
        setTitle("文本文件处理器");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建组件
        textArea = new JTextArea();
        textArea.setLineWrap(true); // 启用自动换行
        // textArea.setWrapStyleWord(true); // 换行时在单词之间换行
        saveButton = new JButton("保存");
        convertButton = new JButton("开始转换");
        resultTextArea = new JTextArea();
        resultTextArea.setLineWrap(true); // 启用自动换行
        // resultTextArea.setWrapStyleWord(true); // 换行时在单词之间换行

        // 为组件设置字体
        Font font = new Font("微软雅黑", Font.PLAIN, 16); // 可根据需要调整字体大小
        textArea.setFont(font);
        saveButton.setFont(font);
        convertButton.setFont(font);
        resultTextArea.setFont(font);

        // 为 JOptionPane 消息对话框设置字体
        UIManager.put("OptionPane.messageFont", font);

        // 创建 JScrollPane 并将文本区域添加到其中
        // JScrollPane scrollPaneTextArea = new JScrollPane(textArea);
        // scrollPaneTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        //
        // JScrollPane scrollPaneResultArea = new JScrollPane(resultTextArea);
        // scrollPaneResultArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        // 创建共享的滚动窗格
        sharedScrollPane = new JScrollPane();
        sharedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);



        // 创建面板
        JPanel westPanel = new JPanel();
        westPanel.setLayout(new BorderLayout());
        westPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
        westPanel.add(saveButton, BorderLayout.SOUTH);

        JPanel eastPanel = new JPanel();
        eastPanel.setLayout(new BorderLayout());
        eastPanel.add(new JScrollPane(resultTextArea), BorderLayout.CENTER);
        eastPanel.add(convertButton, BorderLayout.SOUTH);

        // 将面板添加到窗体中
        getContentPane().setLayout(new GridLayout(1, 2));
        getContentPane().add(westPanel);
        getContentPane().add(eastPanel);

        // 将文本区域添加到共享的滚动窗格中
        sharedScrollPane.setViewportView(textArea);

        // 从 inputFilePath 中加载初始内容
        loadInitialContent();

        // 添加事件监听器
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveToFile();
            }
        });

        convertButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startConversion();
            }
        });
    }

    private void loadInitialContent() {
        // 从 properties 中获取 inputFilePath 的值
        String inputFilePath = properties.getProperty("inputFilePath");
        try {
            String content = new String(Files.readAllBytes(Paths.get(inputFilePath)));
            textArea.setText(content);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "加载初始内容时出错: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveToFile() {
        // 从 properties 中获取 inputFilePath 的值
        String inputFilePath = properties.getProperty("inputFilePath");
        try {
            String content = textArea.getText();
            Files.write(Paths.get(inputFilePath), content.getBytes());
            JOptionPane.showMessageDialog(this, "文件保存成功!");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "保存文件时出错: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void startConversion() {
        // String inputText = textArea.getText().trim(); // 删除前导和尾随空格
        String inputText = textArea.getText(); // 读取首行内容
        // 检查首行是否不为空且以至少两个空格开头
        if (!inputText.isEmpty() && inputText.startsWith("  ")) {
            String convertedText = processLine(inputText);
            resultTextArea.setText(convertedText);

            // 从 properties 中获取 inputFilePath 和 outputDirectory 的值
            String inputFilePath = properties.getProperty("inputFilePath");
            String outputDirectory = properties.getProperty("outputDirectory");

            try {
                try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
                    // 读取第一行文本
                    String firstLine = reader.readLine();
                    if (firstLine != null) {
                        // 找到第二个空格前的所有数据作为文件名
                        int firstSpaceIndex = firstLine.indexOf(' ');
                        if (firstSpaceIndex != -1) {
                            int secondSpaceIndex = firstLine.indexOf(' ', firstSpaceIndex + 1);
                            if (secondSpaceIndex != -1) {
                                String fileName = firstLine.substring(1, secondSpaceIndex);
                                String outputFilePath1 = Paths.get(outputDirectory, fileName + ".txt").toString();
                                Files.write(Paths.get(outputFilePath1), convertedText.getBytes());
                                JOptionPane.showMessageDialog(this, "转换完成并保存到 " + fileName + "!");
                            }
                        }
                    }
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "保存转换后的文件时出错: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "首行必须不为空且以至少两个空格开头才能继续。", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String processLine(String line) {
        for (Object key : properties.keySet()) {
            String strKey = (String) key;
            String value = properties.getProperty(strKey);
            String escapedKey = Pattern.quote(strKey);
            line = line.replaceAll(escapedKey, value);
        }
        return line;
    }

    public static void main(String[] args) {
        Properties defaultProperties = new Properties();
        Properties customProperties = new Properties();

        try (InputStream defaultInputStream = new FileInputStream("src/main/resources/config.properties");
             InputStream customInputStream = new FileInputStream("app.properties")) {
            defaultProperties.load(new InputStreamReader(defaultInputStream, "UTF-8"));
            customProperties.load(new InputStreamReader(customInputStream, "UTF-8"));
        } catch (IOException e) {
            System.err.println("无法加载配置文件: " + e.getMessage());
            return;
        }

        // 合并两个 properties
        Properties mergedProperties = new Properties();
        mergedProperties.putAll(defaultProperties);
        mergedProperties.putAll(customProperties);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TextFileProcessorUI03 ui = new TextFileProcessorUI03(mergedProperties);
                ui.setVisible(true);
            }
        });
    }
}
